package springbook.user.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import springbook.user.domain.Level;
import springbook.user.domain.User;

public class UserDaoJdbc implements UserDao {
	private JdbcTemplate jdbcTemplate;
	private RowMapper<User> userMapper = new RowMapper<User>() {
		@Override
		public User mapRow(ResultSet rs, int rowNumber) throws SQLException {
			User user = new User();
			user.setId(rs.getString("id"));
			user.setName(rs.getString("name"));
			user.setPassword(rs.getString("password"));
			user.setLevel(Level.valueOf(rs.getInt("level")));
			user.setLogin(rs.getInt("login"));
			user.setRecommend(rs.getInt("recommend"));
			return user;
		}
	};

	public UserDaoJdbc() {
		 
	}

	public void setDataSource(DataSource dataSource) {
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}

	@Override
	public int add(User user) {
		return this.jdbcTemplate.update("insert into users values (?, ?, ?, ?, ?, ?)",
				user.getId(),
				user.getName(),
				user.getPassword(),
				user.getLevel().intValue(),
				user.getLogin(),
				user.getRecommend());
	}

	@Override
	public User get(String id) {
		return this.jdbcTemplate.queryForObject("select * from users where id = ?",
					new Object[] {id},
					this.userMapper);
	}

	@Override
	public List<User> getAll() {
		return this.jdbcTemplate.query("select * from users order by id",
					this.userMapper);
	}

	@Override
	public int deleteAll() {
		return this.jdbcTemplate.update("delete from users");
	}

	@Override
	public int getCount() {		
		return this.jdbcTemplate.queryForInt("select count(*) from users");
	}

	@Override
	public int delete(String id) {
		return this.jdbcTemplate.update("delete from users where id = ?", id);
	}

	@Override
	public int update(User user) {
		return this.jdbcTemplate.update(
					"update users set name = ?, password = ?, level = ?, login = ?, " +
					"recommend = ? " + 
					"where id = ?",
					user.getName(),
					user.getPassword(),
					user.getLevel().intValue(),
					user.getLogin(),
					user.getRecommend(),
					user.getId());
	}

}
